package com.atcjx.controller;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.Log;
import com.atcjx.MyUtils.File.UploadGiteeImgBed;
import com.atcjx.MyUtils.IdUtils;
import com.atcjx.MyUtils.ResultFactory;
import com.atcjx.exception.UserException;
import com.atcjx.exception.exceptionEnum;
import com.atcjx.pojo.Result;
import com.atcjx.service.UploadServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author admin
 * @version 1.0.0
 * @ClassName UploadController.java
 * @Description TODO
 * @createTime 2021年09月27日 19:20:00
 */
@Api("上传信息")
@RestController
@RequestMapping("/toUpload")
public class UploadController {

    @Autowired
    UploadServiceImpl uploadService;

    @ApiOperation("上传图片至本地文件中")
    @PostMapping("/img")
    public Result uploadImg(@RequestParam("file") List<MultipartFile> fileList, HttpServletRequest request) throws UserException {
        String imgURL = uploadService.uploadImg(fileList, request);
        return ResultFactory.successWithData(imgURL);
    }

    @ApiOperation("上传md文件到本地文件中")
    @PostMapping("/mdFile")
    public Result uploadMdFile(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws UserException {
        String mdUrl = uploadService.uploadMdFIle(file, request);
        return ResultFactory.successWithData(mdUrl);
    }

    @ApiOperation("上传图片到码云图床")
    @PostMapping("/uploadImg")
    public Result uploadImgToGitee(@RequestParam("file") List<MultipartFile> multipartFileList) throws IOException {
        List<String> urlList = new ArrayList<>();
        for (MultipartFile file : multipartFileList) {
            String url = UploadGiteeImgBed.uploadToGiteePicBed(file);
            urlList.add(url);
            uploadService.storeURL(url,url);
        }
        return ResultFactory.successWithData(urlList);
    }

    @ApiOperation("通过网络URL上传图片到码云图床")
    @PostMapping("/uploadImgByURL")
    public Result uploadImgToGiteeByURL(
            @RequestBody Map<String, String> params) throws Exception {
        String requestURL = params.get("requestURL");
        if(uploadService.checkBaseURL(requestURL)){
            throw new UserException(exceptionEnum.EXSISTIMGURL.getMsg(), exceptionEnum.EXSISTIMGURL.getCode());
        }
        String s = UploadGiteeImgBed.uploadToGiteePicBedByUrl(requestURL);
        uploadService.storeURL(s,requestURL);
        return ResultFactory.successWithData(s);
    }


}
